Skip to content

Conversation

@docto-rin
Copy link
Owner

Comment on lines +43 to +46
without_last, with_last = (
max(without_last, with_last),
without_last + nums[i]
)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私はこの書き方あまり好きではないですが、まあ、しかし新しい変数作るよりは見やすいかもしれませんね。

@docto-rin
Copy link
Owner Author

without_last, with_last = (
    max(without_last, with_last),
    without_last + nums[i]
)

について、関数化:

def step(skip_last, take_last, value):
    next_skip = max(skip_last, take_last)
    next_take = skip_last + value
    return next_skip, next_take

skip_last, take_last = step(skip_last, take_last, nums[i])

functools.reduceを使う:

import functools
import itertools
from typing import Iterable, List, Tuple


class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        if n == 0:
            return 0
        if n == 1:
            return nums[0]

        def rob_linear(sequence):
            def step(state, x):
                skip_last, take_last = state
                next_skip = max(skip_last, take_last)
                next_take = skip_last + x
                return next_skip, next_take

            skip_last, take_last = functools.reduce(step, sequence, (0, 0))
            return max(skip_last, take_last)

        return max(
            rob_linear(itertools.islice(nums, 0, n - 1)),
            rob_linear(itertools.islice(nums, 1, n)),
        )

https://docs.python.org/ja/3.13/library/functools.html#functools.reduce
functools.reduce(function, iterable, [initial_state, ]/)

  • functionについて、
    • 第1引数…累積状態(accumulator, A)
    • 第2引数…イテラブルから取り出した現在要素(X)
    # functionのイメージ
    from typing import Callable
    reducer = Callable[[A, X], A]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants